import { defineStore } from 'pinia';
import apiClient from '@/api.ts';

export interface SettingsState {
  backgroundColor: string;
  fontColor: string;
  blurIntensity: number;
  darkMode: boolean;
  backgroundImage: string;
  cardBlurIntensity: number;
  backgroundColorOpacity: number; // New state for opacity
  siteTitle: string;
  faviconUrl: string;
  isFetched: boolean;
}

// 增强：类型转换工具函数
const parseValue = (key: keyof SettingsState, value: any): any => {
  if (value === null || value === undefined) return null;
  switch (key) {
    case 'darkMode':
      return value === 'true' || value === true;
    case 'blurIntensity':
    case 'cardBlurIntensity':
    case 'backgroundColorOpacity':
      const num = parseFloat(value);
      return isNaN(num) ? null : num;
    default:
      return value;
  }
};

export const useSettingsStore = defineStore('settings', {
  state: (): SettingsState => ({
    backgroundColor: '#000000',
    fontColor: '#e0e0e0',
    blurIntensity: 0,
    darkMode: true,
    backgroundImage: '',
    cardBlurIntensity: 5,
    backgroundColorOpacity: 0.5,
    siteTitle: '我的博客',
    faviconUrl: '/favicon.ico',
    isFetched: false,
  }),
  actions: {
    // 增强：保存到本地存储
    saveSettingsToLocalStorage() {
      try {
        localStorage.setItem('blogSettings', JSON.stringify(this.$state));
      } catch (e) {
        console.error('Failed to save settings to localStorage:', e);
      }
    },

    // 增强：从本地存储加载
    loadSettingsFromLocalStorage() {
      try {
        const savedSettings = localStorage.getItem('blogSettings');
        if (savedSettings) {
          const parsed = JSON.parse(savedSettings);
          // 关键：应用解析和类型转换
          for (const key in parsed) {
            if (this.hasOwnProperty(key)) {
              const typedValue = parseValue(key as keyof SettingsState, parsed[key]);
              if (typedValue !== null) {
                (this as any)[key] = typedValue;
              }
            }
          }
          console.log('Successfully loaded settings from localStorage.');
        }
      } catch (e) {
        console.error('Failed to load settings from localStorage:', e);
      }
    },

    async fetchSettings() {
      if (this.isFetched) return;
      try {
        const response = await apiClient.get('/api/settings');
        if (Object.keys(response.data).length > 0) {
          // 关键：应用解析和类型转换
          for (const key in response.data) {
            if (this.hasOwnProperty(key)) {
              const typedValue = parseValue(key as keyof SettingsState, response.data[key]);
              if (typedValue !== null) {
                (this as any)[key] = typedValue;
              }
            }
          }
          this.saveSettingsToLocalStorage(); // 成功获取后保存
        }
        this.isFetched = true;
      } catch (error) {
        console.error('Failed to fetch settings:', error);
        this.isFetched = true;
      }
    },
    async updateSettings(newSettings: Partial<SettingsState>) {
      try {
        await apiClient.put('/api/settings', newSettings);
        Object.assign(this, newSettings);
        this.saveSettingsToLocalStorage(); // 更新后保存
      } catch (error) {
        console.error('Failed to update settings:', error);
        throw error;
      }
    },
  },
});